const { getUserId } = require('../../utils')

const isOwner = async (ctx, id, userId) => {
  const exist = await ctx.db.exists.Topic({ id, owner: { id: userId } })
  if (!exist) {
    throw new Error('need topic author')
  }
}

const topic = {
  async createTopic (parent, { name, description, partIds }, ctx, info) {
    const userId = getUserId(ctx)
    return ctx.db.mutation.createTopic({
      data: {
        name,
        description,
        owner: {
          connect: {
            id: userId
          }
        },
        parts: {
          connect: partIds
        }
      }
    }, info)
  },
  async updateTopic (parent, { id, name, description, partIds, disconnectPartIds }, ctx, info) {
    const userId = getUserId(ctx)
    // 先判断是否有操作权限
    await isOwner(ctx, id, userId)
    // 这里需要考虑的是当某个参数为空时会不会有影响
    return ctx.db.mutation.updateTopic({
      where: {
        id
      },
      data: {
        name,
        description,
        parts: {
          disconnect: disconnectPartIds,
          connect: partIds
        }
      }
    }, info)
  },
  async deleteTopic (parent, { id }, ctx, info) {
    const userId = getUserId(ctx)
    // 先判断是否有操作权限
    await isOwner(ctx, id, userId)
    return ctx.db.mutation.deleteTopic({
      where: {
        id
      }
    }, info)
  }
}

module.exports = { topic }
